package com.example.administrator.demoa;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements InOnDelListener,InOnClickListener{
    private RecyclerView rvStu;
    private Button btnAdd;
    private EditText edtKey;
    private Button btnSearch;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

        initStu();

        adapter = new StuAdapter(MainActivity.this,studentArrayList,
                MainActivity.this,MainActivity.this);

        readDataFromDB();

        rvStu.setAdapter(adapter);
        //让其显示
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        rvStu.setLayoutManager(manager);
    }

    //从数据库中读取数据
    private void readDataFromDB() {
        //创建或打开数据库
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        //创建学生表
        String sql = "create table if not exists student(stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);

        //每次查询前进行清空
        studentArrayList.clear();

        //查询，进行遍历添加至学生列表中
        Cursor cursor = db.query("student",null,null,
                null,null,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String no = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(no, name, age);
                studentArrayList.add(student);
            }
        }

        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();
    }

    private void initStu() {
        studentArrayList.add(new Student("17001","Lin",18));
        studentArrayList.add(new Student("17002","杨洋",18));
        studentArrayList.add(new Student("17003","杨昊然",18));
    }

    private void findViews() {
        rvStu = findViewById(R.id.rv_stu);
        btnAdd = findViewById(R.id.btn_add);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });

        edtKey = findViewById(R.id.edt_key);
        btnSearch = findViewById(R.id.btn_search);

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = edtKey.getText().toString();
                searchStudentFromDB(key);
            }
        });

        initAutoSearch();
    }

    //自动搜索
    private void initAutoSearch() {
        edtKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = edtKey.getText().toString();
                searchStudentFromDB(key);
            }
        });
    }

    //搜索
    private void searchStudentFromDB(String key) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "stuno like '%"+key+"%' OR name like '%"+key+"%' OR age = '"+key+"'";

        studentArrayList.clear();

        Cursor cursor = db.query("student",null,where,
                null,null,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String no = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(no, name, age);
                studentArrayList.add(student);
            }
        }

        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == 2001){
            Student student = (Student) data.getSerializableExtra("STUDENT");
            addStudentToDB(student);
        }else if(resultCode == 3001){
            Student student = (Student) data.getSerializableExtra("STUDENT");
            updateStudentToDB(student);
        }
    }

    //修改学生
    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "stuno = '"+student.getNo()+"'";
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("age", student.getAge());
        db.update("student",values, where,null);

        db.close();
        readDataFromDB();
    }

    //添加学生至数据库
    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("stuno",student.getNo());
        values.put("name",student.getName());
        values.put("age",student.getAge());
        db.insert("student", null, values);

        db.close();
        readDataFromDB();
    }

    //删除学生
    @Override
    public void del(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        /*//第一种：组装语句
        String sql = "delete from student where stuno = '"+student.getNo()+"'";
        db.execSQL(sql);*/

        /*//第二种：delete接口
        String where = "stuno = '"+student.getNo()+"'";
        db.delete("student", where, null);*/

        //第三种：带参数的接口
        String where = "stuno = ? OR name = ?";
        String[] args = {student.getNo(),student.getName()};
        db.delete("student", where, args);


        db.close();
        readDataFromDB();
    }

    //RecyclerView点击事件
    @Override
    public void click(Student student) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this,EditActivity.class);
        intent.putExtra("STUDENT",student);
        startActivityForResult(intent, 1002);
    }
}
